package com.xiehua.task.job.bucket;

import com.xiehua.task.job.RidesOperationDefualt;
import com.xiehua.task.job.TaskReverse;
import com.xiehua.task.job.TaskReverseDefualt;
import com.xiehua.task.job.pool.DelayJob;
import com.xiehua.task.job.pool.FixedJob;
import com.xiehua.task.job.pool.Job;
import org.tio.utils.json.Json;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xiehua.task.job.pool.DelayJobPool.JOB_POOL_DELAY_KEY;
import static com.xiehua.task.job.pool.Job.JobType.delay;
import static com.xiehua.task.job.pool.Job.JobType.fixed;

public class ReadyBucket extends RidesOperationDefualt {

    // private ConcurrentLinkedQueue<Job> taskQueue;

    public static final String JOB_READY_QUEUE = "task_job_ready_queue";

    public ReadyBucket(Jedis jedis) {
        super(jedis);
    }



    /**
     * 取出一个任务
     **/
    public Job pollTask() {
        String job = jedis.rpop(JOB_READY_QUEUE);
        if (job == null || job.equals("")) return null;
        Job j = Json.toBean(job, Job.class);
        if(delay.equals(j.getType()))return  Json.toBean(job, DelayJob.class);
        if(fixed.equals(j.getType()))return  Json.toBean(job, FixedJob.class);
        return null;
    }

    /**
     * 批量取出任务
     **/
    public List<Job> pollTaskBatch() {
        //init list
//        List<Job> list = new ArrayList<>();
//        jedis.watch(JOB_READY_QUEUE);
//        Transaction transaction = jedis.multi();
//        Long len = jedis.llen(JOB_READY_QUEUE);
//        if (len > 0) {
//            len = len > 200 ? 200 : len;
//            for (int i = 0; i < len; i++) {
//                String job = transaction.rpop(JOB_READY_QUEUE).get();
//                list.add(Json.toBean(job, Job.class));
//            }
//        }
//        transaction.exec();
//        jedis.unwatch();
        List<Job> list = new ArrayList<>();
        Long len = jedis.llen(JOB_READY_QUEUE);
        if (len > 0) {
            len = len > 200 ? 200 : len;
            for (int i = 0; i < len; i++) {
                Job job = pollTask();
                if(job != null) list.add(job);
            }
        }
        return list;
    }

    /***
     * 添加一个任务
     * **/
    public void offerTask(Job job) {
        job.setStatus(Job.JobStatus.ready);
        job.setUpdateTime(LocalDateTime.now());
        jedis.lpush(JOB_READY_QUEUE, Json.toJson(job));

    }

    /***
     * 批量添加任务
     * **/
    public void offerTask(List<Job> jobs) {
       new TaskReverseDefualt(jedis).ready(jobs);
    }


}
